package com.example.campusform.question

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.PopupWindow
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.campusform.Item
import com.example.campusform.ItemAdapter
import com.example.campusform.ItemManager
import com.example.campusform.R
import com.example.campusform.question.QuestionData.itemSelectedList
import com.example.campusform.service.listLiveData
import com.xm.zxn.timeselector.TimeSelector
import com.xm.zxn.timeselector.utils.TextUtil
import kotlinx.android.synthetic.main.activity_new.*
import kotlinx.android.synthetic.main.item_toolbar.view.*
import org.jetbrains.anko.sdk27.coroutines.onCheckedChange
import java.lang.StringBuilder
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

class CreateQuestionsActivity : AppCompatActivity() {
    private var type = QuestionType.SINGLE_QUESTION
    private lateinit var itemManager: ItemManager
    private var startData = ""
    private var endData = ""
    private val arrayList = arrayListOf("单选题", "多选题", "文本题", "十分量表题", "百分量表题", "排序题")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_new)
        tb_new.iv_tb_back.setOnClickListener {
            onBackPressed()
        }
        val today =
            SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(Calendar.getInstance().timeInMillis)
        tv_new_date_begin.text = today
        tv_new_date_end.text = today
        startData = "$today 00:00"
        endData = "$today 23:59"
        tv_new_time_begin.text = "00:00"
        tv_new_time_end.text = "23:59"
        val timeSelectorStart = TimeSelector(
            this, TimeSelector.ResultHandler {
                tv_new_date_begin.text = it.subSequence(0, it.length - 6)
                tv_new_time_begin.text = it.subSequence(it.length - 5, it.length)
                startData = it
            },
            "$today 00:00",
            (Calendar.getInstance(Locale.CHINA).get(Calendar.YEAR) + 1).toString() + "-12-31 23:59"
        ).apply {
            this.setMode(TimeSelector.MODE.YMDHM)
        }
        tv_new_date_begin.setOnClickListener {
            timeSelectorStart.show()
        }
        tv_new_time_begin.setOnClickListener {
            timeSelectorStart.show()
        }
        val timeSelectorEnd = TimeSelector(
            this, TimeSelector.ResultHandler {
                tv_new_date_end.text = it.subSequence(0, it.length - 6)
                tv_new_time_end.text = it.subSequence(it.length - 5, it.length)
                endData = it
            },
            "$today 00:00",
            (Calendar.getInstance(Locale.CHINA).get(Calendar.YEAR) + 1).toString() + "-12-31 23:59"
        ).apply {
            this.setMode(TimeSelector.MODE.YMDHM)
        }
        tv_new_date_end.setOnClickListener {
            timeSelectorEnd.show()
        }
        tv_new_time_end.setOnClickListener {
            timeSelectorEnd.show()
        }
        val view = LayoutInflater.from(this).inflate(R.layout.popup_new_setting, null)
        val popup = PopupWindow(
            view,
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT
        )
        popup.isOutsideTouchable = true
        iv_new_setting.setOnClickListener {
            popup.showAsDropDown(it)
        }
        spinner_new_type.adapter =
            ArrayAdapter<String>(this, R.layout.item_new_spinner, arrayList).apply {
                setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            }
        spinner_new_type.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {
            }

            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                type = when (position) {
                    0 -> QuestionType.SINGLE_QUESTION
                    1 -> QuestionType.MULTI_QUESTION
                    2 -> QuestionType.TEXT_QUESTION
                    3 -> QuestionType.TEN_QUESTION
                    4 -> QuestionType.HUNDRED_QUESTION
                    5 -> QuestionType.SORT_QUESTION
                    else -> {
                        QuestionType.SINGLE_QUESTION
                    }
                }
            }
        }


        itemManager = ItemManager()
        rv_new_questions.adapter = ItemAdapter(itemManager)
        rv_new_questions.layoutManager = LinearLayoutManager(this)

        addQuestion()
        iv_new_add.setOnClickListener {
            addQuestion()
        }
        iv_new_remove.setOnClickListener {
            val itemList = arrayListOf<Item>()
            val questionList = arrayListOf<Question>()
            val snapshot = itemManager.itemListSnapshot
            for (position in itemSelectedList) {
                itemList.add(snapshot[position])
                questionList.add(QuestionData.getQuestion(position))
            }
            for (item in itemList) {
                itemManager.remove(item)
            }
            for (question in questionList) {
                QuestionData.removeQuestion(question)
            }
            itemSelectedList.clear()
        }
        cb_new_all.onCheckedChange { buttonView, isChecked ->
            if (isChecked) {
                val snapshot = itemManager.itemListSnapshot
                itemSelectedList.clear()
                for (item in snapshot.withIndex()) {
                    val it = item.value
                    if (it is Checkable) {
                        it.check(isChecked)
                    }
                    itemSelectedList.add(item.index)
                }

            } else {
                val snapshot = itemManager.itemListSnapshot
                for (item in snapshot) {
                    if (item is Checkable) {
                        item.check(isChecked)
                    }
                }
                itemSelectedList.clear()
            }
        }
        tv_new_submit.setOnClickListener {
//            Toast.makeText(this, "$startData<$endData = ${startData < endData}", Toast.LENGTH_SHORT)
//                .show()
            Log.d("et_new_name", "${et_new_name.text}")
            var builder = StringBuilder()
            if (startData >= endData) {
                builder.append("日期不合规\n")
            }
            if (TextUtil.isEmpty(et_new_name.text.toString())) {
                builder.append("问卷名不能为空\n")
            }
            if (TextUtil.isEmpty(builder.toString())) {
                listLiveData.value = ArrayList(listLiveData.value ?: listOf()).apply {
                    add(et_new_name.text.toString())
                }
                finish()
            } else {
                Toast.makeText(this, builder.toString(), Toast.LENGTH_SHORT).show()
            }

        }
    }

    override fun onDestroy() {
        super.onDestroy()
        QuestionData.clear()
    }

    private fun checkTime(startData: String, endData: String): Boolean {
        return startData < endData
    }

    private fun addQuestion() {
        QuestionData.addQuestion()
        when (type) {
            QuestionType.SINGLE_QUESTION, QuestionType.MULTI_QUESTION, QuestionType.SORT_QUESTION -> {
                QuestionData.addChoice(itemManager.size)
            }
        }
        itemManager.add(ItemFactory.createItem(type, this))

    }
}